package com.zkingsoft.actions.codegen;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.codeApi.Configuration;
import com.zkingsoft.codeApi.DataBaseType;
import com.zkingsoft.codeApi.ModelType;
import com.zkingsoft.codeApi.StringToEnumConverter;
import com.zkingsoft.codeApi.TemplateModel;
import com.zkingsoft.generator.Dbconnection;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ResponseUtils;
import com.zkingsoft.services.GeneratorService;

/**
 * @author 姜友瑶
 * @e-mail:<935090232@qq.com>
 * @date 2015-10-23
 * @description 代码生成器
 */
@Controller
@RequestMapping(value = "/codegen")
public class CodegenController extends BaseController {

	public CodegenController() {
		log.info("CodegenController 创建");
	}

	@Autowired
	GeneratorService generatorService;

	@RequestMapping(value = "/getTableList")
	public String getTableList(HttpServletResponse response, HttpServletRequest request, String url,
			Configuration configuration) {

		configuration.setDataBaseType(DataBaseType.MYSQL);
		configuration.setDriver("com.mysql.jdbc.Driver");
		configuration.setUrl("jdbc:mysql://" + url + "?useUnicode=true&amp;characterEncoding=utf-8");
		configuration.setDbName(url.substring(url.indexOf("/") + 1, url.length()));
		Connection connection = Dbconnection.getConnection(configuration);
		List<String> tablesName = generatorService.getDBtablsName(configuration, connection);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("tables", tablesName);
		ResponseUtils.send(response, result);
		return null;
	}

	// 开始生成文件plush
	@RequestMapping(value = "/generatorUp")
	public String generatorUp(HttpServletResponse response, HttpServletRequest request, Configuration configuration) {
		try {
			log.info("进入生成文件action...");
			// 配置基本信息
			configuration.setDataBaseType(DataBaseType.MYSQL);
			configuration.setDriver("com.mysql.jdbc.Driver");
			configuration.setDbName(configuration.getUrl().substring(configuration.getUrl().indexOf("/") + 1,
					configuration.getUrl().length()));
			configuration
					.setUrl("jdbc:mysql://" + configuration.getUrl() + "?useUnicode=true&amp;characterEncoding=utf-8");
			configuration.setUserTempLataHome(
					java.net.URLDecoder.decode(this.getClass().getResource("/").getPath(),"utf-8") + "template" + File.separator + "java");
			configuration = setSelectModelFiles(configuration);
			Map<String, Object> result = generatorService.generator(configuration);
			String zipName = "code" + DateUtils.getTimeMark() + ".zip";
			response.setContentType(request.getSession().getServletContext().getMimeType(zipName));
			response.setHeader("Content-Disposition", "attachment;filename=" + zipName);
			FileInputStream fileInputStream = null;
			OutputStream out;
			out = response.getOutputStream();
			fileInputStream = new FileInputStream((File) result.get("zipFile"));
			byte[] bufs = new byte[1024 * 10];
			BufferedInputStream bis = new BufferedInputStream(fileInputStream);
			int read = 0;
			while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
				out.write(bufs, 0, read);
			}
			out.flush();
			if (out != null) {
				out.close();
			}
			if (fileInputStream != null) {
				fileInputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			new Thread() {

				public void run() {
					try {
						Thread.sleep(20 * 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					File file2 = new File(this.getClass().getResource("/").getPath() + "temp");
					deleteFile(file2);
				}

			}.start();
		}
		return null;
	}

	/**
	 * 根据用户的选择设置模板的基础信息
	 * 
	 * @param configuration
	 * @return
	 */
	private Configuration setSelectModelFiles(Configuration configuration) {
		Map<ModelType, TemplateModel> templateModels = new HashMap<ModelType, TemplateModel>();
		for (int i = 0; i < configuration.getIsCreateTemplateModelTypeStr().size(); i++) {
			String selectedStr = configuration.getIsCreateTemplateModelTypeStr().get(i);
			if (selectedStr != null) {

				ModelType select = StringToEnumConverter
						.convertToModelType(configuration.getIsCreateTemplateModelTypeStr().get(i));

				if (select != null) {
					TemplateModel model = TemplateModel.getTemplateModel(select);
					
					if (select.equals(ModelType.MYBATIS_DAO_IMPL)) {
						model.setSavePath(configuration.getModelPackages().get(2));
						templateModels.put(ModelType.MYBATIS_DAO_IMPL, model);

					} else if (select.equals(ModelType.SERVICE)) {
						model.setSavePath(configuration.getModelPackages().get(3));
						templateModels.put(ModelType.SERVICE, model);

					} else if (select.equals(ModelType.SERVICE_IMPL)) {
						model.setSavePath(configuration.getModelPackages().get(4));
						templateModels.put(ModelType.SERVICE_IMPL, model);

					} else if (select.equals(ModelType.ACTION)) {
						model.setSavePath(configuration.getModelPackages().get(5));
						templateModels.put(ModelType.ACTION, model);

					} else if (select.equals(ModelType.VIEW)) {
						model.setSavePath(configuration.getModelPackages().get(6));
						templateModels.put(ModelType.VIEW, model);
					}

				}
			}
		}
		configuration.setTemplateModels(templateModels);
		return configuration;
	}
	//递归删除文件夹  
	   private void deleteFile(File file) {  
	    if (file.exists()) {//判断文件是否存在  
	     if (file.isFile()) {//判断是否是文件  
	      file.delete();//删除文件   
	     } else if (file.isDirectory()) {//否则如果它是一个目录  
	      File[] files = file.listFiles();//声明目录下所有的文件 files[];  
	      for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件  
	       this.deleteFile(files[i]);//把每个文件用这个方法进行迭代  
	      }  
	      file.delete();//删除文件夹  
	     }  
	    } else {  
	     System.out.println("所删除的文件不存在");  
	    }  
	   } 
	   public static void main(String[] arg){
			try {
				String configPath = java.net.URLDecoder.decode(CodegenController.class.getResource("/").getPath(),"utf-8");
				System.out.println(configPath);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
}